<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>球撞</title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }
        canvas{
            background: #eeee;
            /* margin:100px 200px; */
        }
    </style>
</head>

<body>
    <canvas id="canvas" width="500" height="500"></canvas>
    <script type="text/javascript">
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        var c1 = {
            x: 90,
            y: 90,
            r: 30,
            color: '#333'
        }
        var c2 = {
            x: 150,
            y: 150,
            r: 30,
            color: '#660066'
        }
        var cs = [c1, c2];
        function init() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            for (var i = 0; i < cs.length; i++) {
                ctx.beginPath();
                ctx.fillStyle = cs[i].color;
                ctx.arc(cs[i].x, cs[i].y, cs[i].r, 0, Math.PI * 2, false);
                ctx.fill();
            }
        }
        init();
         // 碰撞函数
         function isCrash(obj1, obj2) {
            var x = obj1.x - obj2.x;
            var y = obj1.y - obj2.y;
            var distance = Math.sqrt(x*x + y*y);//开方函数
            if(distance < obj1.r + obj2.r) {//判断碰撞
                obj1.speedX = -obj1.speedX;
                obj1.speedY = -obj1.speedY;
                obj2.speedX = -obj2.speedX;
                obj2.speedY = -obj2.speedY;
            }
        }
        canvas.onmousedown = function (e) {
            var ev = e || window.event;
            // // 鼠标坐标
            var x = ev.clientX-10;
            var y = ev.clientY-10;
            init();
            var oldX = x - cs[1].x;
            var oldY = y - cs[1].y;
            canvas.onmousemove = function (e) {
                var ev = e || window.event;
                cs[1].x = ev.clientX - oldX;
                cs[1].y = ev.clientY - oldY;
                init();
                pengZhuang(c1, c2);
            }
        }
        function pengZhuang(obj1, obj2) {
            var dis = obj1.r + obj2.r;
            var DISX = (obj1.x - obj2.x) * (obj1.x - obj2.x);
            var DISY = (obj1.y - obj2.y) * (obj1.y - obj2.y);
            console.log(dis,Math.sqrt(DISX + DISY))
            if (dis >= Math.sqrt(DISX + DISY)) {
                alert("撞上了");
            }
        }
    </script>
</body>

</html>